package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;

import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.entity.SysDict;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.SysUserMapper;
import com.itheima.ydd.service.ISysDictService;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private ISysDictService sysDictService;

    @Override
    public R profile(Long userId) {
        //1.1 查询登录用户信息
        SysUser sysUser = sysUserService.getById(userId);
        //1.2 填入用户角色信息
        LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
        String sysUserRoleId = sysUser.getRoleId();
        sysRoleWrapper.eq(SysRole::getId, sysUserRoleId.substring(2, sysUserRoleId.length() - 2));
//        sysRoleWrapper.select(SysRole::getName);
        //1.2.1 查出对应的角色详细信息
        SysRole sysRole = sysRoleService.getOne(sysRoleWrapper);
        //1.2.2 封装进sysUserDto对象中
        SysUserDto userInfo = new SysUserDto();
        BeanUtils.copyProperties(sysUser, userInfo);
        userInfo.setRolename(sysRole.getName());

        //2 查菜单数据
        LambdaQueryWrapper<SysMenu> sysMenuWrapper = new LambdaQueryWrapper<>();
        sysMenuWrapper.ne(SysMenu::getPath, "");
        List<SysMenu> menuList = sysMenuService.list(sysMenuWrapper);

        //3 dictsList
        LambdaQueryWrapper<SysDict> sysDictWrapper = new LambdaQueryWrapper<>();
        sysDictWrapper.select(SysDict::getType);
        sysDictWrapper.groupBy(SysDict::getType);
        //3.1 分组查询所有dict_type
        List<Object> dictTypes = sysDictService.listObjs(sysDictWrapper);
        Map<String, Map<String, String>> dictsList = new HashMap<>();
        //3.2 遍历dictTypes ，查询对应的dict信息，存入dictsList中
        for (Object o : dictTypes) {
            Map<String, String> map = new HashMap<>();

            sysDictWrapper = new LambdaQueryWrapper<>();
            sysDictWrapper.eq(SysDict::getType, o);
            List<SysDict> sysDicts = sysDictService.list(sysDictWrapper);
            for (SysDict sysDict : sysDicts) {
                //3.3 将dict_value,dict_label存入集合
                map.put(sysDict.getValue(), sysDict.getLabel());
            }

            //3.4 将保存后的数据存入dictsList
            dictsList.put((String) o, map);
        }

        //4 准备 btnList
        Map<Integer, String> btnList = new HashMap<>();
        btnList.put(0, "*");

        //5 将所有查出的数据存入 R 中，返回
        R r = new R();
        r.putData("btnList", btnList);
        r.putData("dictsList", dictsList);
        r.putData("menuList", menuList);
        r.putData("userInfo", userInfo);

        r.setErrno(0);
        r.setErrmsg("");
        return r;
    }

    /**
     * @description: 用户列表分页查询
     * @author: 黄伟兴
     * @date: 2022/9/7 12:33
     * @param: [login_name, status, phone, page, limit]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData getList(String login_name, String status, String phone, Integer page, Integer limit) {
        //查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone)
                .like(StringUtils.isNotEmpty(status), SysUser::getStatus, status)
                .like(StringUtils.isNotEmpty(login_name), SysUser::getLoginName, login_name)
                //被删除的不能查询
                .eq(SysUser::getDelFlag, 0);

        Page<SysUser> pageInfo = page(new Page<SysUser>(page, limit), queryWrapper);
        Page<SysUserDto> dtoPage = new Page<>();

        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<SysUser> records = pageInfo.getRecords();

        List<SysUserDto> list = records.stream().map((item) -> {
            SysUserDto sysUserDto = new SysUserDto();
            BeanUtils.copyProperties(item, sysUserDto, "records");

            String roleId = item.getRoleId().split("\"")[1];
            SysRole role = sysRoleService.getById(roleId);

            // 设置角色名称
            sysUserDto.setRolename(role.getName());
            return sysUserDto;

        }).collect(Collectors.toList());

        dtoPage.setRecords(list);

        //前端要的key与查询出来的key不相符，重新设置map返回
        HashMap<Object, Object> map = new HashMap<>();
        map.put("totalPages", limit);
        map.put("pageSize", dtoPage.getSize());
        map.put("currentPage", dtoPage.getCurrent());
        map.put("count", dtoPage.getTotal());
        map.put("data", dtoPage.getRecords());

        return ResultData.ok("查询成功！", map);
    }

    /**
     * @description: 管理员删除
     * @author: 黄伟兴
     * @date: 2022/9/7 12:36
     * @param: [id]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData deleteById(String id) {
        //1.先查询用户
        SysUser one = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId, id));
        if (one != null) {
            one.setDelFlag("1");
            updateById(one);
            return ResultData.ok("删除成功！", one);
        }
        return ResultData.error("删除失败！");
    }

    /**
     * @description: 查询管理员详情
     * @author: 黄伟兴
     * @date: 2022/9/7 17:09
     * @param: [id]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData getDetail(String id) {
        SysUser sysUser = getById(id);

        String roleIdStr = sysUser.getRoleId();
        String substring = roleIdStr.substring(3, roleIdStr.length() - 3);
        sysUser.setRoleId(substring);


        return ResultData.ok("查询成功！", sysUser);
    }

    /**
     * @description: 添加管理员
     * @author: 黄伟兴
     * @date: 2022/9/7 21:53
     * @param: [userDto]
     * @return: com.itheima.ydd.common.ResultData
     **/
    @Override
    public ResultData add(SysUser user) {

        return ResultData.ok("添加成功",null);
    }


}
